﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

/// <summary>
/// （在主线程）处理消息分发。
/// </summary>
public class CmdEngine : MonoBehaviour
{
    public Dictionary<Type, Action<NCmd.Cmd>> CmdPaserCache = new Dictionary<Type, Action<NCmd.Cmd>>();
    public List<NCmd.Cmd> CmdCache = new List<NCmd.Cmd>();
    // 网络消息，阻塞状态
    private bool _pauseState = false;
    public bool PauseState
    {
        get
        {
            return _pauseState;
        }

        set
        {
            _pauseState = value;
        }
    }

    List<NCmd.Cmd> _pausedCmdCache = new List<NCmd.Cmd>();
    void Update()
    {
        if (PauseState)
        {
            return;
        }

        // 在本组缓存执行中，也要处理阻塞
        foreach (var cmd in CmdCache)
        {
            if (PauseState)
            {
                _pausedCmdCache.Add(cmd);
                continue;
            }
            Action<NCmd.Cmd> callback;
            if (CmdPaserCache.TryGetValue(cmd.GetType(), out callback))
            {
                NetRegister.instance.CheckAndLogRecive(cmd);
                callback.Invoke(cmd);
            }
            else
            {
                Utils.LogWithColor(cmd.ClassName, "[未处理的消息]", "yellow");
            }
        }
        CmdCache.Clear();
        CmdCache.AddRange(_pausedCmdCache);
        _pausedCmdCache.Clear();
    }
}
